﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Tweets.ascx.cs" company="Tobias Lekman">
//   Licensed under Microsoft Public License (Ms-PL). See lekman.codeplex.com/license for more information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace LekmanCom.Controls
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    using LekmanCom.Properties;

    /// <summary>
    /// Control that displays my latest twitter updates.
    /// </summary>
    public partial class Tweets : FeedUserControl
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Tweets"/> class.
        /// </summary>
        public Tweets()
            : base(Resources.TweetFeedUrl)
        {
        }

        #endregion

        #region Methods

        /// <summary>
        /// Called when the XML data binds.
        /// </summary>
        /// <param name="data">
        /// The XML data.
        /// </param>
        protected override void OnDataBind(XElement data)
        {
            IEnumerable<Tweet> message = from tweet in data.Descendants("status")
                                         where IsNotReply(tweet)
                                         select new Tweet(tweet);

            this.TweetsRepeater.DataSource = message.Take(10);
            this.TweetsRepeater.DataBind();
        }

        /// <summary>
        /// Determines whether the specified tweet update is a reply.
        /// </summary>
        /// <param name="tweet">
        /// The tweet update.
        /// </param>
        /// <returns>
        /// <c>true</c> if is not a reply; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsNotReply(XElement tweet)
        {
            XElement element = tweet.Element("text");

            return element == null || !element.Value.StartsWith("@");
        }

        #endregion
    }
}